<script setup>
/**
 * 机柜打开视图，可以看见设备、板卡、端口
 */

import { onMounted } from "vue";
import * as THREE from "three";
import { OrbitControls } from "three/addons/controls/OrbitControls.js";
import { addBoards, getBoards } from "@/js/board";
import { loadCabinetModel } from "@/js/cabinet";
import { parsePort } from "@/js/port";
import { parseSlot } from "@/js/slot";
import { useRouter, useRoute } from "vue-router";
import { toCookiesSave } from "@/js/login";
import { requestJSON } from "@/js/url";
import { addCabinetDevices, getDevices } from "@/js/device";
import threeEvent from "@/js/threeEvent";
import sceneMrg from '../js/sceneMrg'
import deviceMrg from '../js/deviceMrg/index'
defineProps({});

//const router = useRouter();
//const route = useRoute();


function findUrlQuery () {
  let url = window.location.href
  const parsedUrl = new URL(url);

  // 使用 URLSearchParams 解析查询参数
  const params = new URLSearchParams(parsedUrl.search);

  // 创建一个空对象
  const paramsObject = {};

  // 遍历所有参数，并将其添加到对象中
  params.forEach((value, key) => {
    paramsObject[key] = value;
  });

  // 输出结果
  console.log("路径参数新加",paramsObject);
  
  return {
    query:paramsObject
  }

}

let route = findUrlQuery()

function cabinetInfoUrl(id) {
  // return `http://java.3ddcim.com/v1/cabinet_view2/${id}?towards=1`;
  return `/cabinet_view2/${id}?towards=1`;
}

const handleContextMenu = (event) => {
  event.preventDefault(); // 阻止默认的上下文菜单
  console.log('Right-clicked!', event);
  let pdata = {
    type:'cabineback'
  }
  top.window.postMessage({
            serial:"",
            serialnalt:"2",
            })
  window.parent.postMessage(pdata, '*');
  // 在这里添加你想要执行的逻辑
};

function deviceInfoUrl(id) {
  return `/equipment_view_info/${id}?towards=0`;
}

const cabinetID = route.query.id; // 机柜id
if (!cabinetID) {
  throw Error("机柜ID无效");
}

// 相机和机柜的距离
const distanceToCabient = route.query.distance || 2.5;

// 生命周期钩子
onMounted(async () => {
  // 单点登录
  /*
  if ((await toCookiesSave()).code != 0) {
    throw Error("单点登录失败");
  }
  */
  if (process.env.NODE_ENV === 'development') {
    console.log('现在是开发模式');
    if ((await toCookiesSave()).code != 0) {
      throw Error("单点登录失败");
    }
  } else {
    console.log('现在不是开发模式');
  }

  let canvas = document.getElementById("three-root");
  const w = canvas.clientWidth;
  const h = canvas.clientHeight;
    console.log("做个测试0")
  // 渲染器
  const renderer = new THREE.WebGLRenderer({
    canvas: document.getElementById("three-root"),
	// powerPreference: "high-performance",
    antialias: true,
    alpha: true,
  });
  console.log("当前版本1.001")
  renderer.setSize(w, h, false);
  renderer.setAnimationLoop(animation);
  const scene = new THREE.Scene();
  sceneMrg.renderer = renderer
  const camera = new THREE.PerspectiveCamera(70, w / h, 0.01, 10);
  // 控制器
  const controls = new OrbitControls(camera, renderer.domElement);
  // 设置缩放速度
  controls.zoomSpeed = 0.5;
  camera.near = 0.01; // 设置合理的近平面值
  camera.far = 10; // 设置合理的远平面值
  console.log("做个测试1")
// 设置缩放的最小和最大距离
  controls.minDistance = 1;
  controls.maxDistance = 10;
  controls.target.set(0, 1, 0);
  camera.position.set(distanceToCabient, 1, 0.2);
  camera.lookAt(0, 1, 0);
  console.log("做个测试2")
  window.addEventListener("resize", () => {
   
    const w = canvas.clientWidth;
    const h = canvas.clientHeight;
    renderer.setSize(w, h, false);
    camera.aspect = w / h;
    camera.updateProjectionMatrix();
  });

  sceneMrg.camera = camera ;
  sceneMrg.controls = controls ;
  sceneMrg.scene = scene ;
  console.log("做个测试3")
  // 光线
  let ambLight = new THREE.AmbientLight(0xffffff, 3);
  scene.add(ambLight);
  const hemiLight = new THREE.HemisphereLight(0xffffff, 0x8d8d8d, 5);
  hemiLight.position.set(0, 20, 0);
  scene.add(hemiLight);
  threeEvent.init(sceneMrg);
  // const dirLight = new THREE.DirectionalLight(0xffffff, 3);
  // dirLight.position.set(-3, 10, -10);
  // dirLight.castShadow = true;
  // dirLight.shadow.camera.top = 2;
  // dirLight.shadow.camera.bottom = -2;
  // dirLight.shadow.camera.left = -2;
  // dirLight.shadow.camera.right = 2;
  // dirLight.shadow.camera.near = 0.1;
  // dirLight.shadow.camera.far = 40;
  // scene.add(dirLight);

  // 动画混合器，控制器
  let mixers = [];
  let clock = new THREE.Clock();
  // animation
  function animation(time) {
    const delta = clock.getDelta();
    for (const mixer of mixers) mixer.update(delta); // 动画播放
    controls.update()
    renderer.render(scene, camera);
  }
  console.log("做个测试4")
  // // 坐标轴DEBUG
  // const axesHelper = new THREE.AxesHelper(5);
  // scene.add(axesHelper);

  // 设备插槽的宽高
  const deviceSlotWidth = 0.45;
  // const deviceSlotHeight = 0.0445;
  const deviceSlotHeight = 0.045;
  // 设备插槽根节点
  let deviceSlotRoot = new THREE.Object3D();
  // 设备插槽的起始位置
    console.log("做个测试5")
  deviceSlotRoot.position.set(0, 0.0445, 0);
  scene.add(deviceSlotRoot);

  if(route.query.type == 'equipment'){
    
      deviceMrg.start({
        deviceSlotHeight:deviceSlotHeight
      })
      return 
  }
  
  // 加载机柜   华为机柜 60X120X220
  console.log("运行到这里了，准备加载机柜。。。。。。。。。。。。")
  {
    //let obj = await loadCabinetModel("./model/cabinet/华为机柜60x60x220黑色.FBX");

    let obj = await loadCabinetModel("./model/cabinet/huawijigui 60X120X220.FBX");


    scene.add(obj);
    const mixer = new THREE.AnimationMixer(obj);
    let action = mixer.clipAction(obj.animations[0]);
    action.clampWhenFinished = true; // 动画结束时固定，不回到开头
    action.timeScale = 3;
    action.setLoop(THREE.LoopOnce);
    action.play();
    mixers.push(mixer);
  }

  // 加载机柜内各设备
   console.log("运行到这里了，加载机柜内各设备。。。。。。。。。。。。")
  {
    let data = (await requestJSON({ url: cabinetInfoUrl(cabinetID) })).data;
    await addCabinetDevices(data, {
      parentObj: deviceSlotRoot,
      deviceSlotHeight,
    });
  }

  
 
});
</script>

<template>
  <canvas @contextmenu="handleContextMenu" id="three-root"></canvas>
 
</template>

<style scoped>
#three-root {
  display: block;
  width: 100%;
  height: 100%;
}
</style>
